package com.situ.blog.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.situ.blog.pojo.BlogType;
import com.situ.blog.pojo.query.BlogTypeQuery;
import com.situ.blog.service.IBlogTypeService;
import com.situ.blog.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dell
 * @since 2024-09-24
 */
@RestController
@RequestMapping("/blogType")
public class BlogTypeController {

    @Autowired
    private IBlogTypeService blogTypeService;

    @GetMapping("/selectAll")
    public Result selectAll() {
        List<BlogType> blogTypes = blogTypeService.list();
        return Result.ok(blogTypes);
    }

    @GetMapping("/list")
    public Result list(BlogTypeQuery blogTypeQuery) {
        IPage<BlogType> page = new Page<>(blogTypeQuery.getPage(), blogTypeQuery.getLimit());
        QueryWrapper<BlogType> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(!ObjectUtils.isEmpty(blogTypeQuery.getName()), "name", blogTypeQuery.getName());
        queryWrapper.between(!ObjectUtils.isEmpty(blogTypeQuery.getBeginCreateTime()) && !ObjectUtils.isEmpty(blogTypeQuery.getEndCreateTime()),
                "create_time", blogTypeQuery.getBeginCreateTime(), blogTypeQuery.getEndCreateTime());
        blogTypeService.page(page, queryWrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("total", page.getTotal());
        map.put("list", page.getRecords());
        return Result.ok(map);
    }

    @DeleteMapping("/deleteById/{id}")
    public Result deleteById(@PathVariable Integer id) {
        blogTypeService.removeById(id);
        return Result.ok("删除成功");
    }

    @DeleteMapping("/deleteAll/{ids}")
    public Result deleteAll(@PathVariable Integer[] ids) {
        blogTypeService.removeByIds(Arrays.asList(ids));
        return Result.ok("删除成功");
    }

    @PostMapping("/add")
    public Result add(@RequestBody BlogType blogType) {
        blogTypeService.save(blogType);
        return Result.ok("添加成功");
    }

    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        BlogType blogType = blogTypeService.getById(id);
        return Result.ok(blogType);
    }

    @PutMapping("/update")
    public Result update(@RequestBody BlogType blogType) {
        blogTypeService.saveOrUpdate(blogType);
        return Result.ok("更新成功");
    }
}

